﻿<template>
  <div class="problems-container">
    <!-- 页面头部 -->
    <div class="problems-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="main-title">用户管理</h1>
          <p class="subtitle">管理系统中的所有用户，包括添加、编辑和删除用户</p>
        </div>
        <div class="stats-section">
          <div class="stat-item">
            <div class="stat-value">{{ total }}</div>
            <div class="stat-label">用户总数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value active">
              {{ userList.filter(u => u.role === "USER").length }}
            </div>
            <div class="stat-label">活跃用户</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选工具栏 -->
    <div class="filter-toolbar">
      <div class="toolbar-left">
        <el-input v-model="searchParams.username" placeholder="搜索用户名..." prefix-icon="Search" clearable class="search-input" @input="handleSearch" />
        <el-select v-model="searchParams.role" placeholder="角色筛选" clearable class="filter-select" @change="handleSearch">
          <el-option label="管理员" value="ADMIN" />
          <el-option label="普通用户" value="USER" />
        </el-select>
      </div>
      <div class="toolbar-right">
        <el-button type="primary" @click="handleAddUser" class="add-button">
          <el-icon><Plus /></el-icon>
          添加用户
        </el-button>
      </div>
    </div>

    <!-- 用户列表 -->
    <div class="problems-content" v-loading="loading">
      <div class="list-view">
        <el-table :data="userList" class="problems-table" @selection-change="handleSelectionChange" ref="userTable" row-class-name="problem-row">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="用户ID" prop="id" width="90" align="center" />
          <el-table-column label="头像" width="80" align="center">
            <template #default="{ row }">
              <el-avatar :size="40" :src="row.avatar" />
            </template>
          </el-table-column>
          <el-table-column label="用户名" prop="username" min-width="120" align="center" show-overflow-tooltip />
          <el-table-column label="角色" width="100" align="center">
            <template #default="{ row }">
              <div class="status-pill" :class="getRoleClass(row.role)">
                {{ getRoleText(row.role) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" prop="email" min-width="180" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.email || "未设置" }}
            </template>
          </el-table-column>
          <el-table-column label="电话" prop="phone" width="130" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.phone || "未设置" }}
            </template>
          </el-table-column>
          <el-table-column label="注册时间" prop="createdAt" width="160" align="center" show-overflow-tooltip>
            <template #default="{ row }">
              {{ formatDate(row.createdAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button type="primary" link @click="handleEditUser(row)" class="operation-button">编辑</el-button>
                <el-button type="danger" link @click="handleDeleteUser(row)" class="operation-button" :disabled="row.role === 'ADMIN'">删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { Plus } from "@element-plus/icons-vue"
import { formatDate } from "@/utils/format/date"
import { getRoleClass, getRoleText } from "@/utils/business/user/profile"

// 响应式数据
const loading = ref(false)
const userList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedUsers = ref([])
const userTable = ref(null)

// 搜索参数
const searchParams = reactive({
  username: "",
  role: ""
})

/**
 * 加载用户列表
 * 当后端用户管理API实现后，这里需要调用真实的API
 */
const loadUserList = async () => {
  loading.value = true
  try {
    // 等待后端实现用户管理API后调用
    // const response = await getUserList({
    //   pageNum: currentPage.value,
    //   pageSize: pageSize.value,
    //   keyword: searchKeyword.value,
    //   role: filterRole.value,
    //   status: filterStatus.value
    // });
    // userList.value = response.data.records;
    // total.value = response.data.total;

    // 临时使用空数据，避免页面报错
    userList.value = []
    total.value = 0
  } catch (error) {
    ElMessage.error("获取用户列表失败")
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadUserList()
}

// 选择处理
const handleSelectionChange = rows => {
  selectedUsers.value = rows
}

// 分页处理
const handleSizeChange = newSize => {
  pageSize.value = newSize
  currentPage.value = 1
  loadUserList()
}

const handleCurrentChange = newPage => {
  currentPage.value = newPage
  loadUserList()
}

/**
 * 添加用户
 * 打开用户编辑对话框，创建新用户
 */
const handleAddUser = () => {
  ElMessageBox.prompt("请输入新用户信息", "添加用户", {
    confirmButtonText: "创建",
    cancelButtonText: "取消",
    inputPlaceholder: "用户名",
    inputPattern: /^[a-zA-Z0-9_]{3,20}$/,
    inputErrorMessage: "用户名格式不正确（3-20位字母数字下划线）"
  })
    .then(({ value }) => {
      // 当用户管理API实现后，这里调用创建用户的API
      ElMessage.success(`用户 ${value} 创建成功（模拟）`)
      loadUserList()
    })
    .catch(() => {
      // 用户取消操作
    })
}

/**
 * 编辑用户
 * 打开用户编辑对话框，修改用户信息
 */
const handleEditUser = user => {
  ElMessageBox.confirm(`确定要编辑用户 "${user.username}" 吗？`, "编辑用户", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // 当用户管理API实现后，这里打开编辑对话框或跳转到编辑页面
      ElMessage.info(`编辑用户 ${user.username} 功能开发中`)
    })
    .catch(() => {
      // 用户取消操作
    })
}

// 删除用户
const handleDeleteUser = async user => {
  try {
    await ElMessageBox.confirm(`确定要删除用户 "${user.username}" 吗？`, "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    })

    ElMessage.success("删除成功")
    loadUserList()
  } catch {
    ElMessage.info("已取消删除")
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadUserList()
})
</script>

<style scoped lang="scss">
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;

.problems-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  background: $bg-color-layout;
  min-height: 100vh;
}

// 页面头部
.problems-header {
  background: linear-gradient(135deg, $color-primary-light-9, $bg-color-white);
  border: 1px solid $border-color-lighter;
  border-radius: 16px;
  padding: 32px;
  margin-bottom: 24px;
  color: $color-text-primary;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title-section {
      .main-title {
        font-size: 32px;
        font-weight: 700;
        margin: 0 0 8px 0;
      }

      .subtitle {
        font-size: 16px;
        opacity: 0.9;
        margin: 0;
      }
    }

    .stats-section {
      display: flex;
      gap: 32px;

      .stat-item {
        text-align: center;

        .stat-value {
          font-size: 28px;
          font-weight: 700;
          margin-bottom: 4px;
          color: $color-text-primary;

          &.active {
            color: $color-success;
          }
        }

        .stat-label {
          font-size: 14px;
          color: $color-text-secondary;
        }
      }
    }
  }
}

// 筛选工具栏
.filter-toolbar {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .toolbar-left {
    display: flex;
    gap: 16px;
    align-items: center;

    .search-input {
      width: 300px;
    }

    .filter-select {
      width: 120px;
    }
  }

  .toolbar-right {
    .add-button {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  }
}

// 表格内容区域
.problems-content {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  .list-view {
    .problems-table {
      .problem-row {
        cursor: pointer;
        transition: background-color 0.2s ease;

        &:hover {
          background-color: #f8fafc;
        }
      }
    }
  }
}

// 状态指示器样式
.status-pill {
  padding: 4px 12px;
  border-radius: 12px;
  display: inline-block;
  font-size: 12px;
  min-width: 50px;
  text-align: center;
  font-weight: 500;
  transition: all 0.3s ease;

  &.role-admin {
    background-color: #f0f9ff;
    color: #409eff;
    border: 1px solid #b3d8ff;
  }

  &.role-user {
    background-color: #f5f7fa;
    color: #909399;
    border: 1px solid #d3d4d6;
  }
}

// 操作按钮
.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.operation-button {
  font-size: 13px;
  padding: 4px 8px;
}

// 分页
.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 24px;
  background: white;
  border-top: 1px solid #e5e7eb;
}

// 响应式设计
@media (max-width: 768px) {
  .problems-container {
    padding: 16px;
  }

  .problems-header {
    padding: 24px 20px;

    .header-content {
      flex-direction: column;
      gap: 20px;
      text-align: center;

      .stats-section {
        gap: 20px;
      }
    }
  }

  .filter-toolbar {
    flex-direction: column;
    gap: 16px;

    .toolbar-left {
      width: 100%;
      flex-wrap: wrap;

      .search-input {
        width: 100%;
      }
    }

    .toolbar-right {
      width: 100%;

      .add-button {
        width: 100%;
        justify-content: center;
      }
    }
  }
}
</style>
